; docformat = 'rst'
;
; NAME:
;   StrTitleCase
;
;+
; :Categories:
;   Strings
;
; :Purpose:
;   Capitalize first letter of each word

; :Params:
;   Input : string to change into title case
;   
; :Keywords:
;   CR : Insert carriage returns into spaces
;
; :Examples:
;   Overwrite existing variable in netCDF file::
;     IDL> Title_case_string=mr_StrTitleCase('hello there')
;     IDL> print, Title_case_string
;       Hello There
;
; :History:
;   Written by: Matt Rigby, MIT, May 31st 2011
;
;-
Function mr_StrTitleCase, input, CR=CR

  compile_opt idl2, hidden

  output=StrTrim(input, 2)
  len=strlen(output)
  output=strcompress( StrUpCase( strmid(Output, 0, 1) ) + StrLowcase( strmid(Output, 1, len-1) ))
  
  pos=strpos( output, ' ' )
  while pos ne -1 do begin
    StrPut, output, StrUpCase( StrMid(Output, pos+1, 1) ), pos+1
    if keyword_set(CR) then begin
      output=strcompress( strmid(output, 0, pos) + '_' + strmid(output, pos, len - pos + 1) )  ;insert extra space to accomodate !c
      len++
      StrPut, output, '!c', pos

    endif
    pos=strpos( output, ' ', pos+1)
  endwhile

  return, output
  
End